﻿#include "client_asio.h"
#include "boost/bind.hpp"

ClientAsio::ClientAsio() : socket_(io_context_) {
	
}

void ClientAsio::Start(unsigned short port, const char* message) {
	read_buffer_.resize(2048);
	std::string message_string(message);
	std::copy(message_string.begin(), message_string.end(), std::back_inserter(write_buffer_));
	socket_.async_connect(boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), port),
		boost::bind(&ClientAsio::OnConnect, this, boost::asio::placeholders::error));
	thread_ = std::thread([this]() {
		io_context_.run();
	});
}

void ClientAsio::Stop() {
	io_context_.stop();
}

void ClientAsio::Wait() {
	thread_.join();
}

void ClientAsio::OnConnect(boost::system::error_code error) {
	if (!error) {
		socket_.async_write_some(boost::asio::buffer(write_buffer_),
			boost::bind(&ClientAsio::OnWrite, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
	}
}

void ClientAsio::OnRead(boost::system::error_code error, size_t size) {
	if (!error) {
		write_buffer_.resize(2048);
		write_buffer_.swap(read_buffer_);
		write_buffer_.resize(size);
		socket_.async_write_some(boost::asio::buffer(write_buffer_),
			boost::bind(&ClientAsio::OnWrite, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
		++count_;
	}
}

void ClientAsio::OnWrite(boost::system::error_code error, size_t size) {
	if (!error) {
		socket_.async_read_some(boost::asio::buffer(read_buffer_),
			boost::bind(&ClientAsio::OnRead, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
	}
}
